<template>
  <a-table
    class="p-table ant-table-striped"
    v-bind="$props"
    :bordered="true"
    :pagination="false"
    @change="handleChange"
    size="small"
    v-dragWidth="{
      columns: $props.columns,
      id: 'p-table'
    }"
    :scroll="{
      x: $props.scroll && $props.scroll.x ? $props.scroll.x : x,
      y: $props.scroll && $props.scroll.y ? $props.scroll.y : y
    }"
  >
    <template
      :key="filt.slots.filterDropdown"
      v-for="filt in slotsFilterList"
      v-slot:[filt.slots.filterDropdown]="{ confirm, column, clearFilters }"
    >
      <!-- setSelectedKeys  selectedKeys clearFilters
        // @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
       -->
      <div
        @mouseup="mouseup"
        :key="filt.slots.filterDropdown + column.key"
        class="p10"
      >
        <div class="sort-font df jcsb">
          <span
            class="cp"
            :style="{
              color: state[filt.key + 'Sort'] === 'asc' ? '#1989fa' : ''
            }"
            @click="handleSort('asc', filt, confirm)"
          >
            <SortAscendingOutlined />
            <span class="fs12">升序</span>
          </span>
          <span
            class="cp"
            :style="{
              color: state[filt.key + 'Sort'] === 'desc' ? '#1989fa' : ''
            }"
            @click="handleSort('desc', filt, confirm)"
          >
            <SortDescendingOutlined />
            <span class="fs12">降序 </span>
          </span>
          <span></span>
        </div>
        <div v-if="filt.model === 1" class="date-wrap mb10">
          <a-range-picker
            @change="setRangeDate(column.key)"
            v-model:value="state[column.key + 'filterValue']"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div v-if="filt.model === 17" class="date-wrap mb10"></div>
        <section v-else>
          <a-input
            ref="searchInput"
            :placeholder="`搜索${column.title}`"
            @change="e => filterCheckbox(e, filt)"
            v-model:value="state[column.key + 'searchText']"
            style="width: 188px; display: block; margin: 10px 0"
            @pressEnter="handleSearch(confirm, column)"
          />

          <div>
            <!--     :indeterminate="state[column.key + 'indeterminate']"-->
            <a-checkbox
              v-if="column.options.length < 300"
              :indeterminate="state[column.key + 'indeterminate']"
              v-model:checked="state[column.key + 'CheckAll']"
              @change="e => onCheckAllChange(e, column)"
            >
              全选
              <span
                >({{
                  state[column.key + 'filterValue']
                    ? state[column.key + 'filterValue'].length
                    : 0
                }}/ {{ column.options.length }})</span
              >
            </a-checkbox>
            <span v-if="column.options.length >= 300"
              >({{
                state[column.key + 'filterValue']
                  ? state[column.key + 'filterValue'].length
                  : 0
              }}/ {{ column.options.length }})</span
            >
            <a-divider dashed />
            <div class="maxh200 os minh40">
              <a-checkbox-group
                @change="e => changeCheckbox(e, column)"
                v-model:value="state[column.key + 'filterValue']"
                name="checkboxgroup"
                :options="column.filterOptions || column.options"
              >
              </a-checkbox-group>
            </div>
          </div>
        </section>
        <div class="mt10 mb10">
          <a-button
            type="primary"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="handleSearch(confirm, column)"
          >
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button
            size="small"
            style="width: 90px"
            @click="handleReset(confirm, column, clearFilters)"
          >
            重置
          </a-button>
        </div>
      </div>
    </template>

    <template
      v-for="item in slotsList"
      :key="item.slots && item.slots.customRender"
      v-slot:[item.slots&&item.slots.customRender]="{ record, index }"
    >
      <template v-if="record">
        <slot
          :record="record"
          :index="index"
          :name="item.slots ? item.slots.customRender : ''"
        >
          {{ record[item.dataIndex] }}
        </slot>
      </template>
    </template>
  </a-table>

  <div
    ref="pagination"
    v-if="$props.hasPaginate && pageInfo"
    class="df jcsb p10"
    style="padding-bottom: 0"
  >
    <div class="o06">
      {{
        `共 ${pageInfo.total || 0}条数据，第${pageInfo.pageNum}/${Math.ceil(
          (pageInfo.total || 0) / pageInfo.pageSize
        )}页`
      }}
    </div>
    <div>
      <a-pagination
        size="small"
        :page-size="pageInfo.pageSize"
        v-model:current="pageInfo.pageNum"
        :total="pageInfo.total"
        @change="changePage"
        @showSizeChange="changePage"
        :pageSizeOptions="['20', '50', '100', '150', '200']"
        show-size-changer
        show-quick-jumper
      />
    </div>
  </div>
</template>
<script>
import { Table } from 'ant-design-vue'
import fetchApply from '@/server/axios'
import {
  reactive,
  toRefs,
  ref,
  computed,
  inject,
  onMounted,
  onUnmounted
} from 'vue'
import {
  SearchOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined
} from '@ant-design/icons-vue'
import { debounce } from 'lodash-es'
import ResizeObserver from 'resize-observer-polyfill'
export default {
  components: {
    SearchOutlined,
    SortAscendingOutlined,
    SortDescendingOutlined
  },
  props: {
    ...Table.props,
    hasPaginate: {
      type: Boolean,
      default: true
    },
    filterUrl: {
      type: String,
      default: '/config/list-column'
    },
    queryFields: {
      type: Array,
      default: () => []
    }
  },
  emits: ['changeCheckbox', 'searchByFilter', 'changePage'],
  setup(props, { emit }) {
    const pagination = ref()
    const pageInfo = props.pagination || inject('pageInfo')
    const slotsList = computed(() => {
      return props.columns.filter(_ => _.slots && _.slots.customRender)
    })
    const slotsFilterKeys = reactive({}) // 用于更新页面

    const refreshClumns = () => {
      props.columns.forEach(_ => {
        // _.filterValue = []
        // _.desc = ''
        // _.filtered = false
        // _.filterOptions = null
        // 给columns 增加字段
        if (_.slots && _.slots.filterDropdown) {
          slotsFilterKeys[_.key] = 0 // 增加key 作为关键字，触发复选框更新
          slotsFilterKeys[_.key + 'CheckAll'] = false
          slotsFilterKeys[_.key + 'FilterValue'] = _.filterValue || []
          slotsFilterKeys[_.key + 'SearchText'] = ''
          slotsFilterKeys[_.key + 'indeterminate'] = false
          slotsFilterKeys[_.key + 'Sort'] = ''
          // _.searchText = '' //  增加搜索关键字
          // _.indeterminate = false
          _.onFilterDropdownVisibleChange = visible => {
            // 收起回调
            if (!visible) {
              _.filtered = !!_.filterValue.length || !!state[_.key + 'Sort']
              console.log(_.filtered, state[_.key + 'Sort'])
            } else {
              fetchQueryList(_)
            }
          }
        }
      })
    }
    refreshClumns()

    const slotsFilterList = computed(() => {
      return (
        props.columns.length > 0 &&
        props.columns.filter(_ => _.slots && _.slots.filterDropdown)
      )
    })

    const state = reactive({
      ...slotsFilterKeys,
      y: 400,
      mouseup(e) {
        e.preventDefault()
        e.stopPropagation()
      },
      handleReset(confirm, column, clearFilters) {
        column.filterValue = []
        column.filterOptions = null
        state[column.key + 'filterValue'] = []
        state[column.key + 'Sort'] = ''
        state[column.key + 'searchText'] = ''
        state[column.key + 'CheckAll'] = false
        state[column.key + 'indeterminate'] = false
        column.desc = ''
        column.filtered = false
        confirm()
        state.updatedDom(column) /// 用于更新页面_
        clearFilters()
        props.columns.forEach(_ => {
          if (_.key === column.key) {
            _.filterValue = []
            _.desc = ''
          }
        })
        emit('searchByFilter', state.getFilterParams())
      },
      updatedDom(column) {
        state[column.key]++ // 用于更新页面
      },
      onCheckAllChange(e, column) {
        state[column.key + 'indeterminate'] = false
        if (e.target.checked) {
          Object.assign(state, {
            [column.key + 'filterValue']: column.options.map(ii => ii.value)
          })
          props.columns.forEach(_ => {
            _.key === column.key &&
              (_.filterValue = state[column.key + 'filterValue'])
          })
        } else {
          state[column.key + 'filterValue'] = []
          props.columns.forEach(_ => {
            _.key === column.key && (_.filterValue = [])
          })
        }
      },
      handleChange(pagination, filters, sorter) {
        emit('handleChange', pagination, filters, sorter)
      },
      handleSort(sort, filt, comfirm) {
        // e.preventDefault()
        // e.stopPropagation()
        state[filt.key + 'Sort'] = sort
        filt.desc = sort
        // state[filt.key + 'indeterminate'] = true
        filt.filtered = true
        // comfirm()
        emit('searchByFilter')
        console.log(comfirm)
      },
      handleSearch(comfirm, column) {
        column.filtered = !!column.filterValue.length
        comfirm()
        emit('searchByFilter', state.getFilterParams())
      },
      // 获取过滤的筛选条件
      getFilterParams() {
        const query = { sortList: [] }
        props.columns.forEach(_ => {
          if (_.desc) {
            query.sortList.push({
              desc: _.desc,
              field: _.dataIndex
            })
          }
          if (_.filterValue && _.filterValue.length) {
            query[_.key] = _.filterValue
          }
        })
        return query
      },
      setRangeDate(key) {
        props.columns.forEach(_ => {
          _.key === key && (_.filterValue = state[key + 'filterValue'])
        })
      },
      changeCheckbox(e, column) {
        console.log(props.columns, 'columns')
        state[column.key + 'filterValue'] = e
        state[column.key + 'indeterminate'] = false

        if (e.length === column.options.length) {
          state[column.key + 'CheckAll'] = true
        } else {
          state[column.key + 'CheckAll'] = false
          state[column.key + 'indeterminate'] = true
        }
        if (e.length === 0) {
          state[column.key + 'indeterminate'] = false
        }
        props.columns.forEach(_ => {
          _.key === column.key && (_.filterValue = e)
        })
      }
    })
    const fetchQueryList = async item => {
      // config/list-column
      // item.options = []
      if (props.queryFields?.length) {
        item.params.queryFields = props.queryFields
      }
      console.log(item.params)
      if (item.filterOptions && item.filterOptions.length === 0) {
        item.filterOptions = null
      }
      const res = await fetchApply(props.filterUrl, item.params)
      item.options = (res.data || []).map(_ => {
        return {
          label: _.value || '空',
          value: _.key || ''
        }
      })
    }
    const filterCheckbox = debounce((e, column) => {
      if (e.target.value) {
        column.filterOptions = column.options.filter(
          _ =>
            _.label &&
            _.label.toLowerCase().includes(e.target.value.trim().toLowerCase())
        )
      } else {
        column.filterOptions = column.options
      }
      console.log(column.filterOptions)
    }, 300)
    const changePage = (page, size) => {
      pageInfo.pageNum = page
      pageInfo.pageSize = size
      emit('changePage', page, size)
    }
    let re = null
    const resizeWidth = () => {
      re = new ResizeObserver(
        debounce(() => {
          const bodyHeight = document.body.offsetHeight
          const { top } = document
            .querySelector('.p-table .ant-table-thead')
            .getBoundingClientRect()
          const height = document.querySelector(
            '.p-table .ant-table-thead'
          ).offsetHeight
          // console.log(window.location.href)
          // console.log(bodyHeight, top, height)
          state.y = bodyHeight - top - height - 58
        }, 300)
      )
      re.observe(document.body)
    }
    onMounted(() => {
      resizeWidth()
    })
    onUnmounted(() => {
      re.disconnect()
    })
    return {
      ...toRefs(state),
      state,
      pagination,
      changePage,
      resizeWidth,
      pageInfo,
      slotsList,
      filterCheckbox,
      slotsFilterList,
      fetchQueryList
    }
  }
}
</script>
<style scoped>
:deep(.ant-checkbox-wrapper) {
  display: block;
  text-indent: 1em;
}
:deep(.ant-divider-horizontal) {
  margin: 5px;
  border-color: #a5a5a5;
}
.sort-font {
  font-size: 22px;
  color: #747270;
}
.maxh200 {
  max-height: 200px;
}
.minh40 {
  min-height: 40px;
}
.os {
  overflow: scroll;
}
</style>
<style lang="scss" scoped>
.p-table {
  :deep .ant-table-small {
    .ant-table-row-cell-break-word {
      padding: 6px 8px !important;
    }
    .ant-btn-link {
      height: 22px;
      padding: 0;
      padding-right: 8px;
    }
  }
}

.ant-table-striped :deep {
  .table-striped td {
    background: #fafafa;
  }
}
</style>
